import { fileURLToPath, URL } from 'url'
import path from 'path'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import AuroImport from 'unplugin-auto-import/vite'
import postcssPxtorem from 'postcss-pxtorem'

export default ({ mode }) => {
  return defineConfig({
    base: loadEnv(mode, process.cwd()).VITE_BASE_PATH,
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
        directoryAsNamespace: true,
        dirs: ['src/component']
      }),
      AuroImport({
        imports: ['vue', 'vue-router']
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      port: 5000,
      host: '127.0.0.1',
      open: true,
      overlay: {
        warnings: false,
        errors: true
      },
      proxy: {
        '/api-service': {
          target: 'https://waterboss.bestimade.com',
          // target: 'http://localhost:8097',
          secure: false,
          changeOrigin: true
        },
        '/admin-service': {
          target: 'https://waterboss.bestimade.com',
          // target: 'http://localhost:8081',
          secure: false,
          changeOrigin: true
        }
      },
      headers: {
        'Access-Control-Allow-Origin': '*'
      }
    },
    build: {
      outDir: 'dist',
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: false,
          drop_debugger: true
        }
      },
      // rollupOptions: {
      //   output: {
      //     manualChunks(id) {
      //       // 将pinia的全局库实例打包进vendor，避免和页面一起打包造成资源重复引入
      //       if (id.includes(path.resolve(__dirname, 'src/stores/index.js'))) {
      //         return 'vendor'
      //       }
      //     }
      //   }
      // },
      minify: 'terser'
    },
    css: {
      postcss: {
        plugins: [
          postcssPxtorem({
            rootValue: 37.5,
            unitPrecision: 5,
            propList: ['*']
          })
        ]
      }
    }
  })
}
